package me.shurufa.widget.smoothcamera.util;


import android.content.Context;
import android.content.res.Resources;
import android.util.DisplayMetrics;

import java.lang.reflect.Method;

public final class DeviceUtil {

    private static DisplayMetrics displayMetrics = null;

    public static int getScreenHeightForCamera(Context context) {
        if (displayMetrics == null) {
            setDisplayMetrics(context.getResources().getDisplayMetrics());
        }
        return displayMetrics.heightPixels;
    }

    public static int getScreenWidthForCamera(Context context) {
        if (displayMetrics == null) {
            setDisplayMetrics(context.getResources().getDisplayMetrics());
        }
        return displayMetrics.widthPixels + getNavigationBarHeight(context);
    }

    public static int getScreenHeight(Context context) {
        if (displayMetrics == null) {
            setDisplayMetrics(context.getResources().getDisplayMetrics());
        }
        return displayMetrics.heightPixels;
    }

    public static int getScreenWidth(Context context) {
        if (displayMetrics == null) {
            setDisplayMetrics(context.getResources().getDisplayMetrics());
        }
        return displayMetrics.widthPixels;
    }


    public static void setDisplayMetrics(DisplayMetrics DisplayMetrics) {
        displayMetrics = DisplayMetrics;
    }

    /**
     * 检查是否有NavigationBar
     * @param context
     * @return 是否有NavigationBar
     */
    private static boolean checkDeviceHasNavigationBar(Context context) {
        boolean hasNavigationBar = false;
        Resources rs = context.getResources();
        int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
        if (id > 0) {
            hasNavigationBar = rs.getBoolean(id);
        }
        try {
            Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
            Method m = systemPropertiesClass.getMethod("get", String.class);
            String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
            if ("1".equals(navBarOverride)) {
                hasNavigationBar = false;
            } else if ("0".equals(navBarOverride)) {
                hasNavigationBar = true;
            }
        } catch (Exception e) {
        }

        return hasNavigationBar;

    }

    /**
     * 获得Navigationbar的高度
     * @param context
     * @return 高度
     */
    private static int getNavigationBarHeight(Context context) {
        int navigationBarHeight = 0;
        Resources rs = context.getResources();
        int id = rs.getIdentifier("navigation_bar_height", "dimen", "android");
        if (id > 0 && checkDeviceHasNavigationBar(context)) {
            navigationBarHeight = rs.getDimensionPixelSize(id);
        }
        return navigationBarHeight;
    }

}
